﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using Spring.Data.NHibernate.Support;
using Spring.Threading;

namespace ShopSpace.Infrastructure.Data
{
	/// <summary>
	/// Wraps the SessionScope object according the
	/// needs of the application
	/// </summary>
	public class UnitOfWork : IDisposable
	{
		#region IDisposable Members

		private SessionScope sessionScope;

		public UnitOfWork(ISessionFactory sessionFactory)
		{
			if (sessionFactory == null)
			{
				throw new ArgumentNullException("sessionFactory");
			}
			SessionScopeSettings settings = new SessionScopeSettings(sessionFactory);
			settings.DefaultFlushMode = FlushMode.Commit;
			sessionScope = new SessionScope(settings, true);
		}

		static UnitOfWork()
		{
			Spring.Threading.LogicalThreadContext.SetStorage(new HybridContextStorage());
		}

		public void Dispose()
		{
			if (this.sessionScope != null)
			{
				this.sessionScope.Close();
				this.sessionScope.Dispose();
			}
		}

		#endregion
	}
}